package com.steakliu.sun.ratelimiter;

import com.steakliu.sun.ratelimiter.api.AbstractRateLimiter;
import com.steakliu.sun.spi.annotation.Join;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * 功能说明：
 * <p>
 * Original @Author: steakliu-刘牌, 2023-02-07  21:25
 * <p>
 * Copyright (C)2020-2022  steakliu All rights reserved.
 */
@Join
public class SemaphoreRateLimiter extends AbstractRateLimiter {

    private final Logger LOGGER = LoggerFactory.getLogger(SemaphoreRateLimiter.class);

    private Semaphore semaphore;

    @Override
    public boolean tryAcquire() {
        try {
            return semaphore.tryAcquire();
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }

    @Override
    public void release() {
        semaphore.release();
    }

    @Override
    public void init(int milliseconds, int permits) {
        super.init(milliseconds, permits);
        this.semaphore = new Semaphore(permits);
    }
}
